<?php
	class UserModel extends Model {
		public function __construct(){
			//$this->open(Model::MYSQL);
			//$this->calledClass(get_class($this));
		}
		public function numRows($result){
			$this->open(Model::MYSQL);
			return is_resource($result)?mysql_num_rows($result):null;
		}
		public function checkRecord($table,$fields=array(),$where=array()){
			$this->open(Model::MYSQL);
			if($table!="" && is_array($fields) && is_array($where)){
				$query = "SELECT ";
				foreach( $fields AS $field ) $fieldname[] = $field ;
				$query .= implode( " , " , $fieldname ) ;
				foreach ( $where AS $field => $value )
					$condition[] = $field . " '" . $value . "'";
				$query .= " FROM " . $table . " WHERE " . implode( " AND " , $condition ) . ";" ;
				return ($this->numRows($this->query($query))==1)?true:false;
			}
		}
		public function checkSession($sessionId,$ip){
			$this->open(Model::MYSQL);
			if($sessionId!=""&&$ip!=""){
				$query = "SELECT sessionid,ip FROM Sessions WHERE sessionid='".$sessionId."' AND ip='".$ip."'";
				if(mysql_num_rows($this->query($query))==1){
					$duration = $this->getFieldValue("Sessions",array("duration"),array("sessionid="=>$sessionId,"ip="=>$ip));
					$duration = is_array($duration)&&!empty($duration)?$duration[0]->duration:0;
					$duration = intval(str_replace("mn","",$duration));
					$loggedtime = $this->getFieldValue("Sessions",array("logged"),array("sessionid="=>$sessionId,"ip="=>$ip)) ;
					$loggedtime = is_array($loggedtime)&&!empty($loggedtime)?$loggedtime[0]->logged:0;
					return $this->getMinute($loggedtime)>=$duration?true:false;
				}
			}
		}
		public function getMinute($time=""){
			if($time!=""&&!empty($time)){
				return intval(time()-strtotime($time)/60);
			}
		}
		public function saveUserSession($fields=array()){
			$this->open(Model::MYSQL);
			if($fields!=null && is_array($fields)){
				foreach ($fields AS $fieldName => $fieldValue ){
					$field[] = $fieldName;
					$value[] = $fieldValue;
				}
				$query = "INSERT INTO Sessions (" . implode(" , " , $field) . ") VALUES('" . implode("' , '" , $value ) . "')" ;
				return $this->query($query);
			}
		}
		public function getFieldValue($table,$field=array(),$where=array()){
			$this->open(Model::MYSQL);
			return parent::getFieldValue($table,$field,$where);
		}
		public function getSessionId($userid,$ip){
			$this->open(Model::MYSQL);
			$result = parent::query("SELECT sessionid FROM Sessions WHERE userid='$userid' AND ip='$ip' ORDER BY logged LIMIT 0,1");
			return mysql_fetch_object($result)->sessionid;
		}
	}